<template>
    <div id="app">
        <nav class="navbar navbar-expand-lg navbar-light" style="background-color: #e3f2fd;">
            <div class="container">
                <router-link class="navbar-brand" to="/"><i class="far fa-gem"></i></router-link>
                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="collapse navbar-collapse" id="navbarSupportedContent">
                    <ul class="navbar-nav mr-auto">
                    <li class="nav-item active">
                        <router-link class="nav-link" to="/">返回首页<span class="sr-only">(current)</span></router-link>
                    </li>
                    </ul>
                    <ul class="navbar-nav ml-auto">			
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                            <i class="fas fa-user pr-2"></i><span v-if="getCurUserInfo">{{getCurUserInfo.username}}</span>
                        </a>
                        <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                            <a class="dropdown-item" href="#" @click="quitUser">退出</a>
                        </div>
                    </li>	
                    </ul>
                </div>
            </div>
        </nav>	
        <div class="container">
            <div class="row mt-4">
                <div class="col-md-4 col-sm-2 mb-4">
                    <div class="list-group" id="list-tab" role="tablist">
                    <a class="list-group-item list-group-item-action active" id="list-home-list" data-toggle="list" href="#user-management" role="tab">
                        用户管理
                    </a>
                    <a class="list-group-item list-group-item-action" id="list-profile-list" data-toggle="list" href="#goods-management" role="tab">
                        商品管理
                    </a>
                    </div>			
                </div>
                <div class="col-md-8 col-sm-10">
                    <div class="tab-content" id="nav-tabContent">
                    <!-- 第一个内容块 -->
                    <div class="tab-pane fade show active" id="user-management">			  
                        <table class="table table-striped text-center" align="center">
                        <thead>
                            <tr>
                            <th scope="col">Id</th>
                            <th scope="col">用户名</th>
                            <th scope="col">当前状态</th>
                            <th scope="col">操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="(item,index) in getUserInfo" :key="index">
                                <td>{{item.id}}</td>
                                <td>{{item.username}}</td>
                                <td> 
                                    <select 
                                    name="userStatus" 
                                    class="container form-control col-md-6 col-sm-12" 
                                    :disabled="!item.selected"
                                    v-model="item.userStatus"
                                    >
                                        <option value="active">有效</option>
                                        <option value="deny">禁止</option>
                                    </select>  
                                </td>
                                <td>
                                    <a class="btn btn-danger" v-if="!item.selected" @click="selectedWhichOne(item.id)">修改</a>
                                    <a class="btn btn-success" v-else @click="editUserStatus(item.id,item.userStatus)">确定</a>
                                </td>
                            </tr>
                        </tbody>
                        </table>
                        <div class="row mb-4">
                            <div class="col-12">
                                <div class="input-group mx-auto" style="max-width:30rem;">
                                    <input type="text" class="form-control" placeholder="请输入用户名" required v-model="userKeyword">
                                    <div class="input-group-prepend">
                                    <span class="input-group-text" id="inputGroupPrepend">搜索</span>
                                    </div>
                                </div>
                            </div>	
                        </div>	                        				  
                    </div>
                    <!-- 第二个内容块 -->
                    <div class="tab-pane fade" id="goods-management">
                        <table class="table table-striped text-center" align="center">
                            <thead>
                                <tr>
                                    <th scope="col">Id</th>
                                    <th scope="col">商品名称</th>
                                    <th scope="col">
                                        类目：
                                        <select name="cid" style="color: #495057;border: 1px solid #ced4da;" v-model="goodKeyWord">
                                            <option value="0">--请选择--</option>
                                            <option value="1">女装</option>
                                            <option value="2">母婴</option>
                                            <option value="3">美妆</option>
                                            <option value="4">居家日用</option>
                                            <option value="5">鞋品</option>
                                            <option value="6">美食</option>
                                            <option value="7">文娱车品</option>
                                            <option value="8">数码家电</option>
                                            <option value="9">男装</option>
                                            <option value="10">内衣</option>
                                            <option value="11">箱包</option>
                                            <option value="12">配饰</option>
                                            <option value="13">户外运动</option>
                                            <option value="14">家装家纺</option>
                                        </select>
                                    </th>
                                    <th scope="col">操作</th>
                                </tr>
                            </thead>
                            <tbody v-if="filtersGoods">
                                <tr v-if="filtersGoods.length==0">
                                    <td colspan="4">当前分类下无商品！</td>
                                </tr>                                
                                <tr v-for="(item,index) in filtersGoods" :key="item.ID" >
                                    
                                    <td>{{item.ID}}</td>
                                    <td>{{item.D_title.substring(0,12)}}</td>
                                    <td>
                                        <select 
                                        name="cid" 
                                        class="container form-control col-md-8 col-sm-12" 
                                        :disabled="!item.selected" 
                                        ref="goodCat"
                                        >
                                            <option value="1"  :selected="item.Cid==1">女装</option>
                                            <option value="2"  :selected="item.Cid==2">母婴</option>
                                            <option value="3"  :selected="item.Cid==3">美妆</option>
                                            <option value="4"  :selected="item.Cid==4">居家日用</option>
                                            <option value="5"  :selected="item.Cid==5">鞋品</option>
                                            <option value="6"  :selected="item.Cid==6">美食</option>
                                            <option value="7"  :selected="item.Cid==7">文娱车品</option>
                                            <option value="8"  :selected="item.Cid==8">数码家电</option>
                                            <option value="9"  :selected="item.Cid==9">男装</option>
                                            <option value="10" :selected="item.Cid==10">内衣</option>
                                            <option value="11" :selected="item.Cid==11">箱包</option>
                                            <option value="12" :selected="item.Cid==12">配饰</option>
                                            <option value="13" :selected="item.Cid==13">户外运动</option>
                                            <option value="14" :selected="item.Cid==14">家装家纺</option>
                                        </select>  
                                    </td>
                                    <td>
                                        <a class="btn btn-danger" v-if="!item.selected" @click="selectedWhichOneGoods(item.ID)">修改</a>
                                        <a class="btn btn-success" v-else @click="editGoodsCat(item.ID,$refs.goodCat[index].value)">确定</a>
                                    </td>
                                </tr>
                                
                            </tbody>
                        </table>
                        <nav v-if="goodKeyWord==0">
                            <ul class="pagination justify-content-center">
                                <li :class="whichGoods==n-1?'page-item active':'page-item'" v-for="n in totalPage" :key="n">
                                    <a class="page-link" href="###" @click="whichGoods=n-1">{{n}}</a>
                                </li>
                                <li :class="whichGoods+1==totalPage ? 'page-item disabled':'page-item'" @click="whichGoods+1==totalPage?isHaveGoods('end'):whichGoods+=1;">
                                    <a class="page-link" href="###">下一页</a>
                                </li>
                            </ul>
                        </nav>                        
                    </div>
                    </div>				
                </div>
            </div>
        </div>
    </div>
</template>

<script>
export default {
data(){
    return {
        userKeyword:'',
        goods:[],
        whichGoods:0,
        goodKeyWord:0,
        totalPage:0,       
    }
},
created(){
    this.getGoodInfo();
}, 
watch:{
    goods(){
      this.addLocalGoodsCat();
    }
},   
computed:{
    getUserInfo() {
        return this.$store.getters.getUser.sort((a,b)=>{
            return a.id - b.id;
        }).filter(item=>{
            if(item.username.includes(this.userKeyword)) return true;
        });
    }, 
    filtersGoods(){
        return this.goods[this.whichGoods] &&  this.goods[this.whichGoods].filter(wantGoods=>{
            if(this.goodKeyWord==0){
                if(String(wantGoods["Cid"]).includes('')){
                    return true;
                }
            }else{
                if(wantGoods["Cid"]==this.goodKeyWord){
                    return true;
                }
            } 
        });
    },
    getCurUserInfo(){ 
        return this.$store.getters.getUser.filter(item=>{
            if(item.id==this.$route.query.id) return true;
        })[0];
    },                           
},
methods:{
    getGoodInfo(){
        this.axios.get("./goodInfo.json").then(result=>{
        this.goods=this.splitArray(result.data.result,10);
        this.totalPage=this.goods.length;
        })
    },
    splitArray(goodsData,splitNum="20"){
        let start=0;
        let end=goodsData.length;
        let newArray=[];
        while(start < end){
            newArray.push(goodsData.slice(start,start+=splitNum))
        }
        return newArray;
    }, 
    selectedWhichOne(userId){
        this.$store.commit("changeSelectedWhichOne",userId);
    },
    editUserStatus(userId,newStatus){
        this.$store.commit("changeSelectedWhichOne",'');
        this.$store.commit("changeSelectedUserStatus",{userId,newStatus});
        if(localStorage.getItem('newUserStatus') != null){
            let LocalUserStatusData =JSON.parse(localStorage.getItem('newUserStatus'));
            let find=false;
            for(let i=0;i<LocalUserStatusData.length;i++){
                if(LocalUserStatusData[i].userId==userId){
                    LocalUserStatusData.splice(i,1,{userId:userId,userStatus:newStatus});
                    find=true;
                    break;
                }
            }
            if(find){
                localStorage.setItem('newUserStatus',JSON.stringify(LocalUserStatusData));  
            }else{
                LocalUserStatusData.push({userId:userId,userStatus:newStatus});
                localStorage.setItem('newUserStatus',JSON.stringify(LocalUserStatusData));            
            }
                        
        }else{
            localStorage.setItem('newUserStatus',JSON.stringify([{
                userId:userId,
                userStatus:newStatus
            }]));
        }
        
    },
    isHaveGoods(type=""){
        if(type=='end'){
            this.whichGoods=this.totalPage-1;
            alert("朋友，我也是有底线的！")
        }else{
            this.whichGoods=0;
            alert("我已经是第一页了！")
        }
    },
    selectedWhichOneGoods(goodId=""){
        this.goods.forEach((item,index)=>{
            if(Array.isArray(item)){
                this.hasMoreArrayGoods(item,goodId);
            }else{
                if(item.ID==goodId){
                    this.$set(item,'selected',true);
                }else{
                    this.$set(item,'selected',false);
                }                    
            }
        })
    },
    hasMoreArrayGoods(goods,goodId,goodsCid){
        if(goodsCid){
            goods.forEach((item,index)=>{
                if(item.ID==goodId){
                    this.$set(item,"Cid",Number.parseInt(goodsCid));
                }
            })
        }else{
            goods.forEach((item,index)=>{
                if(item.ID==goodId){
                    this.$set(item,'selected',true);
                }else{
                    this.$set(item,'selected',false);
                }
            })
        }
    },
    editGoodsCat(goodId,goodsCid){
        //console.log(goodId,goodsCid)
        this.goods.forEach((item,index)=>{
            if(Array.isArray(item)){
                this.hasMoreArrayGoods(item,goodId,goodsCid);
            }else{
                if(item.ID==goodId){
                    this.$set(item.Cid,"Cid",Number.parseInt(goodsCid));
                }                
            }
        })
        this.selectedWhichOneGoods("");

        if(localStorage.getItem('newGoodsCat') != null){
            let LocalGoodsCatData =JSON.parse(localStorage.getItem('newGoodsCat'));
            let find=false;
            for(let i=0;i<LocalGoodsCatData.length;i++){
                if(LocalGoodsCatData[i].ID==goodId){
                    LocalGoodsCatData.splice(i,1,{ID:goodId,Cid:goodsCid});
                    find=true;
                    break;
                }
            }
            if(find){
                localStorage.setItem('newGoodsCat',JSON.stringify(LocalGoodsCatData));  
            }else{
                LocalGoodsCatData.push({ID:goodId,Cid:goodsCid});
                localStorage.setItem('newGoodsCat',JSON.stringify(LocalGoodsCatData));            
            }
                        
        }else{
            localStorage.setItem('newGoodsCat',JSON.stringify([{
                ID:goodId,
                Cid:goodsCid
            }]));
        }






    },
    quitUser(){
        let userInfo=this.getCurUserInfo;
        this.$store.commit("addIsCreate",-1);
        this.deleteCookie(userInfo.id,userInfo.username, -2);
        this.$store.commit("changeLoginStatus");
        this.$store.commit("clearShopCart");
        alert('退出成功，准备前往首页');
        this.$router.push('/');
    },
    deleteCookie(userId, userName, expires) {
        let Days = expires;
        let exp = new Date();
        exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
        document.cookie = `id=${userId};expires=${exp.toGMTString()}`;
        document.cookie = `username=${encodeURI(userName)};expires=${exp.toGMTString()}`;
    },
    addLocalGoodsCat(){
        if(localStorage.getItem('newGoodsCat')!=null){
            let localGoodsCat=JSON.parse(localStorage.getItem('newGoodsCat'));
            for(let item of this.goods){
                if(Array.isArray(item)){
                    for(let item2 of item){
                    
                        for(let item3 of localGoodsCat){
                            if(item3.ID==item2.ID) this.$set(item2,'Cid',item3.Cid)
                        }
                    }
                }
            }
        }
    },                     
}
}
</script>


<style scoped>
.table td{
    vertical-align: middle;
}
a:not([href]):not([tabindex]){
    color:#fff
}
</style>
